/**
*找出对象中的对应值
*@param {Object} obj 对象
*@param {string} template 模板名
*/
export function getObjectValue(obj, template) {
  if (template && obj) {
    let value = obj
    let namelist = template.split('.')
    for (const name of namelist) {
      if (value[name]) value = value[name]
      else return undefined
    }
    return value
  }
}

/**
*设置对象中的对应值
*@param {Object} obj 对象
*@param {string} template 模板名
*@param {*} newValue 新设置的值
*/
export function setObjectValue(obj, template, newValue) {
  if (template && obj) {
    let temp = obj
    let namelist = template.split('.')
    for (let i = 0; i < namelist.length - 1; i++) {
      if (temp[namelist[i]]) temp = temp[namelist[i]]
      else return
    }
    if (temp) temp[namelist[namelist.length - 1]] = newValue
  }
}

/**
*对象合并,JSON方法不能合并代理对象
*@param {Object} obj1 对象
*@param {Object} obj2 对象
*/
export function mergeObj(obj1, obj2) {
  if (!obj1) {
    return clone(obj2)
  } else if (!obj2) {
    return clone(obj1)
  } else {
    let mergeObj = {}
    let obj1Names = Object.getOwnPropertyNames(obj1)
    for (const name of obj1Names) {
      mergeObj[name] = clone(obj1[name])
    }
    let obj2Names = Object.getOwnPropertyNames(obj2)
    for (const name of obj2Names) {
      mergeObj[name] = clone(obj2[name])
    }
    return mergeObj
  }
}

/**
*克隆对象(数组)
*@param {Object} obj 对象
*/
function clone(obj) {
  if (obj instanceof Array) {
    return cloneAry(obj)
  } else if (obj instanceof Object) {
    return cloneObj(obj)
  } else {
    return obj
  }
}

/**
*克隆对象
*@param {Object} obj 对象
*/
function cloneObj(obj) {
  let tempObj = {}
  let names = Object.getOwnPropertyNames(obj)
  for (const name of names) {
    tempObj[name] = clone(obj[name])
  }
  return tempObj
}

/**
*克隆数组
*@param {Array} array 对象
*/
function cloneAry(array) {
  let tempAry = new Array(array.length)
  for (let i = 0; i < tempAry.length; i++) {
    tempAry[i] = clone(array[i])
  }
  return tempAry
}

/**
*取得环境变量
*@param {Object} dataObj 对象
*@param {VNode} vnode VNode类
*/
export function getEnv(dataObj, vnode) {
  let env = mergeObj(dataObj, vnode.env)
  env = mergeObj(env, vnode.computed)
  return env
}